import java.util.Random;


public class Guess implements State
{
	private FSMachine			m_fsm;
	private int myID;
	
	public Guess(FSMachine fsm)
	{
		m_fsm = fsm;		
	}
	
	public void Enter(int myID, int otherID)
	{
		//System.out.println("Guess - Enter");
		this.myID = myID;
	}
	
	public void Execute()
	{
		//System.out.println("Guess - Execute");
		Agent me = Global.agents.get(myID);
		// don't change states (or do anything) if we're busy doing something else.
		if (!me.isBusy) {
			Random r = new Random();
			// If I'm the killer, I want to move to my enemy. If someone is in the process
			// of dying, don't do this. Go talk to a friend instead.
			if (me.isKiller()) {
                                if(!Global.killInProgress){
				int fsel = r.nextInt(me.getEnemies().size());
				
				int count = 0;
				while (!Global.agents.get(me.getEnemies().get(fsel)).isLiving) {
					fsel = r.nextInt(me.getEnemies().size());
					count++;
					if (count > 20) {
						break;
					}
				}
                                System.out.println("I WILL KILL "+me.getEnemies().get(fsel)+"######################");
                                m_fsm.ChangeState(FSMachine.enumState.KILLAGENT, myID, me.getEnemies().get(fsel));

//                                if (!Global.agents.get(me.getEnemies().get(fsel)).isBusy) {
//					m_fsm.ChangeState(FSMachine.enumState.MOVETO, me.agentid,
//							me.getEnemies().get(fsel));
//				} else {
//					// TODO add handling for the other agent being busy
//                                        System.out.println("FFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUU I CAN'T KILL HIM! I WILL SNIPE THE MAN");
//                                        m_fsm.ChangeState(FSMachine.enumState.KILLAGENT, myID, me.getEnemies().get(fsel));
//                                }
                                }
			} else {
				// If I'm not the killer, I want to move to my friend.
				int fsel = r.nextInt(me.getFriends().size());
				// If my friend is not alive, I need to choose another.
				while (!Global.agents.get(me.getFriends().get(fsel)).isLiving) {
					fsel = r.nextInt(me.getFriends().size());
				}
				Agent selectedAgent = Global.agents.get(me.getFriends().get(fsel));
				if (!(selectedAgent.isBusy || selectedAgent.isKiller())) {
					try {
						m_fsm.ChangeState(FSMachine.enumState.MOVETO,
								me.agentid, me.getFriends().get(fsel));
					} catch (StackOverflowError se) {
						System.out.println("ERROR CAUGHT!");
					}
				} else {
					// TODO add handling for the other agent being busy WANDER
				}
			}
		}
	}
	
	public void Exit()
	{
		//System.out.println("Guess - Exit");
	}
}
